import React, { useEffect, useState } from "react";
import Cropper from "react-easy-crop";
import { Button, Mask, Space } from "antd-mobile";
import "./style.scss";
import $fetch from "../../app/$fetch";

const CropImage: any = ({ src, visible, form, avatar, dispatch, from = 'login' }: any) => {
  const [crop, setCrop] = useState<any>({ x: 0, y: 0 });
  const [zoom, setZoom] = useState<any>(1);
  const [rotation, setRotation] = useState<any>(0);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<any>(null);

  const getRadianAngle = (degreeValue: any) => {
    return (degreeValue * Math.PI) / 180;
  };

  const createImage = (url: any) => {
    return new Promise((resolve, reject) => {
      const image = new Image();
      image.addEventListener("load", () => resolve(image));
      image.addEventListener("error", (error) => reject(error));
      image.setAttribute("crossOrigin", "anonymous"); // needed to avoid cross-origin issues on CodeSandbox
      image.src = url;
    });
  };

  const rotateSize = (width: any, height: any, rotation: any) => {
    const rotRad = getRadianAngle(rotation);

    return {
      width:
        Math.abs(Math.cos(rotRad) * width) +
        Math.abs(Math.sin(rotRad) * height),
      height:
        Math.abs(Math.sin(rotRad) * width) +
        Math.abs(Math.cos(rotRad) * height),
    };
  };

  // const handleCancel = async () => {
  //   try {
  //     const formData = new FormData();
  //     if (avatar instanceof File) {
  //       formData.append("file", avatar);
  //       const res: any = await $fetch("/minio/upload", formData, {
  //         method: "post",
  //         noGroupId: "no",
  //         dataType: "form",
  //         loading: false,
  //       });
  //       form.setFieldsValue({
  //         avatar: [{ url: res?.url }],
  //       });
  //       dispatch({ avatar: [{ url: res?.url }], showCropper: false });
  //     }
  //   } catch (error) {
  //     console.log(error, "______error");
  //   }
  // };

  const handleCancel = ()=>{
    dispatch({ avatar: [{ url: '' }], showCropper: false });
  }

  const handleConfirm: any = async () => {
    if (croppedAreaPixels !== null && src) {
      const image: any = await createImage(src);
      const canvas = document.createElement("canvas");
      const ctx: any = canvas.getContext("2d");
      if (!ctx) {
        return null;
      }
      const rotRad = getRadianAngle(rotation);
      const { width: bBoxWidth, height: bBoxHeight } = rotateSize(
        image.width,
        image.height,
        rotation
      );
      // set canvas size to match the bounding box
      canvas.width = bBoxWidth;
      canvas.height = bBoxHeight;

      const flip = { horizontal: false, vertical: false };

      ctx.translate(bBoxWidth / 2, bBoxHeight / 2);
      ctx.rotate(rotRad);
      ctx.scale(flip.horizontal ? -1 : 1, flip.vertical ? -1 : 1);
      ctx.translate(-image.width / 2, -image.height / 2);

      // draw rotated image
      ctx.drawImage(image, 0, 0);

      const croppedCanvas = document.createElement("canvas");

      const croppedCtx = croppedCanvas.getContext("2d");

      if (!croppedCtx) {
        return null;
      }

      croppedCanvas.width = croppedAreaPixels.width;
      croppedCanvas.height = croppedAreaPixels.height;

      croppedCtx.drawImage(
        canvas,
        croppedAreaPixels.x,
        croppedAreaPixels.y,
        croppedAreaPixels.width,
        croppedAreaPixels.height,
        0,
        0,
        croppedAreaPixels.width,
        croppedAreaPixels.height
      );

      const croppedImage: any = await new Promise((resolve, reject) => {
        croppedCanvas.toBlob((file: any) => {
          resolve(URL.createObjectURL(file))
        }, 'image/jpeg')
      })
      dispatch({ img: croppedImage, showCropper: false  })

      new Promise((resolve, reject) => {
        croppedCanvas.toBlob((file: any) => {
          resolve(file);
        }, "image/jpeg", 0.7);
      }).then(async (data: any) => {
        const formData: any = new FormData();
        const file = new File([data], `${Math.random()}`, {
          type: "image/png",
        });
        formData.append("file", file);
        // for (let [key, value] of formData.entries()) {
        //   console.log(key, value);
        // }
        const res: any = await $fetch("/minio/upload", formData, {
          method: "post",
          noGroupId: "no",
          dataType: "form",
          loading: false,
        });

           
        // if (from === 'personal') {
        //   form.setFieldsValue({
        //     avatarnone: [{ url: res?.url }],
        //   });
        // } else {
        //   form.setFieldsValue({
        //     avatar: [{ url: res?.url }],
        //   });
        // }
        dispatch({ avatar: [{ url: res?.url }]});
        // dispatch({ showCropper: false });
      });
    }
  };
  return (
    <Mask visible={visible}>
      <Cropper
        image={src}
        cropShape="round"
        cropSize={{ width: 300, height: 300 }}
        crop={crop}
        zoom={zoom}
        aspect={4 / 3}
        onCropChange={setCrop}
        onRotationChange={setRotation}
        onCropComplete={(croppedArea, croppedAreaPixels) =>
          setCroppedAreaPixels(croppedAreaPixels)
        }
        onZoomChange={(e: any) => {
          setZoom(e);
        }}
      />
      <Space wrap className='footer_btn'>
        <Button block onClick={handleCancel}>
          取消
        </Button>
        <Button block onClick={handleConfirm}>
          确认
        </Button>
      </Space>
    </Mask>
  );
};

export default CropImage;
